import { Toolkit } from "../Framework/scripts/Toolkit";
import CanDrag from "./editor/CanDrag";
import Editor from "./editor/Editor";

const { ccclass, property } = cc._decorator;

@ccclass
export default class DragItem extends cc.Component {

    @property(cc.Sprite)
    icon: cc.Sprite;

    canDrag: CanDrag;
    stage: cc.Node;
    seleted: cc.Node = null;
    public static currentDragObj: DragItem = null;
    onLoad() {

        //this.node.addComponent(CanDrag);
        this.node.on(cc.Node.EventType.MOUSE_DOWN, (e: cc.Event.EventMouse) => {
            if (e.getButton() === cc.Event.EventMouse.BUTTON_LEFT) {
                Toolkit.logTrace("拖拽");
                if (DragItem.currentDragObj == this) return;
                DragItem.currentDragObj = this;
                this.stage = Editor.instance.center;
                let src = this.node.convertToWorldSpaceAR(cc.Vec2.ZERO);
                let lp = this.stage.convertToNodeSpaceAR(src);
                // this.node.setParent(this.stage);
                // this.node.setPosition(lp);

                let n: cc.Node = null;
                if (this.seleted == null) {
                    n = new cc.Node(this.node.name);
                    n.addComponent(cc.Sprite).spriteFrame = this.icon.spriteFrame;
                    n.name = this.icon.spriteFrame.name;
                    n.width = this.node.width;
                    n.height = this.node.height;
                    n.setParent(this.stage);
                    n.setPosition(lp.addSelf(cc.v2(lp.x > 0 ? -10 : 10, 10)));
                    this.canDrag = n.addComponent(CanDrag);
                    this.seleted = n;
                    this.canDrag.add_drag_event(()=>{
                        Editor.instance.guide(n);
                    },this);
                }
                else {
                    n = this.seleted;
                    cc.tween(n).to(0.5, { color: cc.Color.RED }).to(0.5, { color: cc.Color.WHITE }).start();
                }
                // let event = new cc.Event.EventTouch([e.getLocation()],false);
                // n.emit(cc.Node.EventType.TOUCH_START,event);
                //this.node.off(cc.Node.EventType.MOUSE_DOWN);
            }
        }, this);
    }

    reset() {
        DragItem.currentDragObj = null;
        this.seleted.destroy();
        this.seleted = null;
        Editor.instance.gfx.clear();
    }

}
